<template>
  <div class="route-simulation">
    <TopNavigation :showOrganizationSection="false" :showTaskRoleSection="false" />
    <div class="page-header">
      <h2>全流程投演管理</h2>
    </div>
    
    <!-- 标签页导航 -->
    <div class="tabs">
      <button 
        class="tab-button" 
        :class="{ active: activeTab === 'config' }"
        @click="activeTab = 'config'"
      >
        统计配置
      </button>
      <button 
        class="tab-button" 
        :class="{ active: activeTab === 'summary' }"
        @click="activeTab = 'summary'"
      >
        投产情况汇总
      </button>
    </div>
    
    <!-- 统计配置界面 -->
    <div v-if="activeTab === 'config'" class="tab-content">
      <!-- 阶段配置 -->
      <div class="card">
        <div class="toolbar">
          <div class="header-info">
            <h3>统计配置管理</h3>
            <p class="subtitle">配置工作流阶段的任务分配，用于统计分析</p>
          </div>
          <button 
            class="btn btn-primary"
            @click="showAddStageModal"
          >
            新建阶段
          </button>
        </div>
        
        <!-- 阶段列表 -->
        <div class="stages-container">
          <div v-if="stages.length === 0" class="empty-state">
            <div class="empty-icon">📊</div>
            <div class="empty-text">暂无工作流数据</div>
            <div class="empty-hint">请确保后端已配置工作流数据</div>
          </div>
          
          <div v-else class="stages-list">
            <div 
              v-for="stage in stages" 
              :key="stage.id" 
              class="stage-item"
              :class="{ 'dragging': dragState.isDragging && dragState.draggingId === stage.id }"
              @dragstart="handleDragStart($event, stage.id)"
              @dragover="handleDragOver($event, stage.id)"
              @drop="handleDrop(stage.id)"
              draggable
            >
              <!-- 阶段头部信息 -->
              <div class="stage-header">
                <div class="stage-info">
                  <div class="stage-number">{{ stage.order }}</div>
                  <div class="stage-name">{{ stage.name }}</div>
                  <div v-if="stage.description" class="stage-description" style="font-size: var(--font-size-sm); color: var(--text-secondary); margin-top: 4px;">{{ stage.description }}</div>
                </div>
                
                <!-- 阶段操作按钮 -->
                <div class="stage-actions">
                  <div class="stage-meta" style="font-size: var(--font-size-xs); color: var(--text-secondary); margin-bottom: 8px;">
                    <span v-if="stage.createdAt">创建于: {{ formatDate(stage.createdAt) }}</span>
                    <span v-if="stage.updatedAt" style="margin-left: 10px;">更新于: {{ formatDate(stage.updatedAt) }}</span>
                  </div>
                  <div class="stage-buttons btn-group">
                    <button 
                      class="btn btn-default btn-sm"
                      @click.stop="showEditStageModal(stage)"
                      title="编辑"
                    >
                      ✏️
                    </button>
                    <button 
                      class="btn btn-default btn-sm"
                      @click.stop="showDeleteConfirmModal(stage.id)"
                      title="删除"
                    >
                      🗑️
                    </button>
                    <button 
                      class="btn btn-default btn-sm"
                      @click.stop="moveStageUp(stage.order)"
                      :disabled="stage.order === 1"
                      title="上移"
                    >
                      ⬆️
                    </button>
                    <button 
                      class="btn btn-default btn-sm"
                      @click.stop="moveStageDown(stage.order)"
                      :disabled="stage.order === stages.length"
                      title="下移"
                    >
                      ⬇️
                    </button>
                  </div>
                </div>
              </div>
              
              <!-- 任务选择区域 -->
              <div class="stage-tasks">
                <div class="section-title">任务分配</div>
                
                <!-- 已选任务展示 -->
                <div v-if="stage.selectedTasks.length > 0" class="selected-tasks">
                  <span 
                    v-for="task in stage.selectedTasks" 
                    :key="task"
                    class="task-tag"
                  >
                    {{ task }}
                    <button 
                      class="remove-task-btn"
                      @click.stop="removeTask(stage.id, task)"
                    >
                      ×
                    </button>
                  </span>
                </div>
                
                <!-- 可选任务列表 -->
                <div class="available-tasks">
                  <label 
                    v-for="taskType in availableTaskTypes" 
                    :key="taskType.id"
                    class="task-checkbox"
                  >
                    <input 
                      type="checkbox" 
                      :checked="stage.selectedTasks.includes(taskType.taskName)"
                      @change="toggleTask(stage.id, taskType.taskName)"
                    />
                    <span class="task-label">{{ taskType.taskName }}</span>
                  </label>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 投产情况汇总界面 -->
    <div v-if="activeTab === 'summary'" class="tab-content">
      <div class="card">
        <div class="toolbar">
          <h3>投产情况汇总</h3>
        </div>
        
        <!-- 搜索栏 -->
        <div class="search-bar">
          <div class="search-fields">
            <div class="search-item">
              <label class="search-label">ECOS版本</label>
              <select v-model="searchForm.ecosVersion" class="select" @change="onEcosVersionChange">
                <option value="">全部版本</option>
                <option v-for="version in ecosVersions" :key="version" :value="version">
                  {{ version }}
                </option>
              </select>
            </div>
            <div class="search-item">
              <label class="search-label">部门</label>
              <select v-model="searchForm.department" class="select" :disabled="!searchForm.ecosVersion" @change="onDepartmentChange">
                <option value="">全部部门</option>
                <option v-for="dept in departments" :key="dept.id" :value="dept.dep">
                  {{ dept.dep }}
                </option>
              </select>
            </div>
            <div class="search-item">
              <label class="search-label">应用名称</label>
              <select v-model="searchForm.application" class="select" :disabled="!searchForm.ecosVersion || !searchForm.department">
                <option value="">全部应用</option>
                <option v-for="app in applications" :key="app" :value="app">
                  {{ app }}
                </option>
              </select>
            </div>
          </div>
          <div class="search-actions">
            <button class="btn btn-primary" @click="performSearch" :disabled="!searchForm.ecosVersion">搜索</button>
          </div>
        </div>
        
        <!-- 搜索结果区域 -->
        <div v-if="showSearchResults" class="search-results">
          <!-- ECOS版本结果 -->
          <div class="result-section">
            <div class="result-header" @click="toggleResultVisibility('ecos')">
              <h4>ECOS版本: {{ searchForm.ecosVersion }} <span class="expand-icon">{{ isEcosExpanded ? '▼' : '▶' }}</span></h4>
            </div>
            <div v-if="isEcosExpanded" class="result-content">
              <div class="process-flow">
                <h5>版本投产流程</h5>
                <div class="flow-container">
                  <div v-for="(stage, index) in versionStages" :key="stage.id" class="flow-stage clickable-stage"
                       @click="showStageProgress('version', stage)">
                    <div class="stage-dot" :class="{ 'completed': getStageCompletion('version', stage) === 100 }" :style="{ backgroundColor: getStageColor('version', stage) }"></div>
                    <div class="stage-name">{{ stage.name }}</div>
                    <div v-if="index < versionStages.length - 1" class="stage-line"></div>
                  </div>
                </div>
              </div>
            </div>

            <div v-if="stageProgress.version.showDetails" class="progress-details-container">
            <div class="progress-details-card">
              <div class="progress-details-header">
                <h3 class="progress-details-title">{{ stageProgress.version.stage.name }} - 进度详情</h3>
                <button class="btn btn-default" @click="clearStageProgress('version')">×</button>
              </div>
              <div class="progress-details-body">
                <!-- 整体进度 -->
                <div class="progress-overview">
                  <h4>整体进度</h4>
                  <div class="progress-card">
                    <div class="progress-info">
                      <span class="progress-percentage">{{ stageProgress.version.progress }}%</span>
                      <span class="progress-label">完成度</span>
                    </div>
                    <div class="progress-bar">
                      <div class="progress-fill" :style="{ width: stageProgress.version.progress + '%' }"></div>
                    </div>
                  </div>
                </div>
                
                <!-- 各子任务进度 -->
                <div class="subtasks-progress">
                  <h4>任务完成度</h4>
                  <div class="subtasks-list">
                    <div v-for="task in stageProgress.version.tasks" :key="task.name" class="subtask-item">
                      <div class="subtask-header">
                        <span class="subtask-name">{{ task.name }}</span>
                        <span class="subtask-percentage">{{ task.progress }}%</span>
                      </div>
                      <div class="progress-bar">
                        <div class="progress-fill" :style="{ width: task.progress + '%', backgroundColor: getTaskColor(task.progress) }"></div>
                      </div>
                      <!-- 任务状态统计 -->
                      <div class="task-stats" style="margin-top: 8px; display: flex; gap: 15px; font-size: 12px;">
                        <span class="stat-item"><span class="completed">已完成:</span> {{ task.completedTasks }}</span>
                        <span class="stat-item"><span class="pending">待处理:</span> {{ task.pendingTasks }}</span>
                        <span class="stat-item"><span class="processing">处理中:</span> {{ task.processingTasks }}</span>
                        <span class="stat-item"><span class="rejected">已拒绝:</span> {{ task.rejectedTasks }}</span>
                        <span class="stat-item"><span class="skipped">已跳过:</span> {{ task.skippedTasks }}</span>
                      </div>
                    </div>
                  </div>
                </div>
                
                <!-- 处理人统计 -->
                <div class="processors-statistics">
                  <h4>处理人统计</h4>
                  <div class="processors-list">
                    <div v-for="processor in stageProgress.version.processors" :key="processor.userId" class="processor-item">
                      <div class="processor-name">{{ processor.userName }}
                        <span class="processor-id" style="font-size: 12px; color: #8c8c8c; margin-left: 10px;">
                          (用户ID: {{ processor.userId }} | 认证ID: {{ processor.userAuthId }})
                        </span>
                      </div>
                      <div class="processor-stats" style="margin-top: 8px;">
                        <div class="stat-item">
                          <span class="stat-label">任务总数:</span>
                          <span class="stat-value">{{ processor.totalTasks }}</span>
                        </div>
                        <div class="stat-item">
                          <span class="stat-label completed">已完成:</span>
                          <span class="stat-value solved">{{ processor.completedTasks }}</span>
                        </div>
                        <div class="stat-item">
                          <span class="stat-label pending">待处理:</span>
                          <span class="stat-value pending">{{ processor.pendingTasks }}</span>
                        </div>
                        <div class="stat-item">
                          <span class="stat-label processing">处理中:</span>
                          <span class="stat-value processing">{{ processor.processingTasks }}</span>
                        </div>
                      </div>
                      <div class="progress-bar" style="margin-top: 10px; display: flex; height: 8px; background-color: #f0f0f0; border-radius: 4px; overflow: hidden;">
                          <div 
                            class="progress-fill solved" 
                            :style="{
                              width: processor.totalTasks > 0 ? (processor.completedTasks / processor.totalTasks * 100) + '%' : '0%',
                              backgroundColor: '#52c41a',
                              transition: 'width 0.3s ease'
                            }"
                          ></div>
                          <div 
                            class="progress-fill processing" 
                            :style="{
                              width: processor.totalTasks > 0 ? (processor.processingTasks / processor.totalTasks * 100) + '%' : '0%',
                              backgroundColor: '#1890ff',
                              transition: 'width 0.3s ease'
                            }"
                          ></div>
                          <div 
                            class="progress-fill pending" 
                            :style="{
                              width: processor.totalTasks > 0 ? ((processor.totalTasks - processor.completedTasks - processor.processingTasks) / processor.totalTasks * 100) + '%' : '100%',
                              backgroundColor: '#faad14',
                              transition: 'width 0.3s ease'
                            }"
                          ></div>
                        </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          </div>
          
          <!-- 部门结果 -->
          <div v-if="searchForm.department" class="result-section">
            <div class="result-header" @click="toggleResultVisibility('department')">
              <h4>部门: {{ searchForm.department }} <span class="expand-icon">{{ isDepartmentExpanded ? '▼' : '▶' }}</span></h4>
            </div>
            <div v-if="isDepartmentExpanded" class="result-content">
              <div class="process-flow">
                <h5>部门投产流程</h5>
                <div class="flow-container">
                  <div v-for="(stage, index) in departmentStages" :key="stage.id" class="flow-stage clickable-stage"
                       @click="showStageProgress('department', stage)">
                    <div class="stage-dot" :class="{ 'completed': getStageCompletion('department', stage) === 100 }" :style="{ backgroundColor: getStageColor('department', stage) }"></div>
                    <div class="stage-name">{{ stage.name }}</div>
                    <div v-if="index < departmentStages.length - 1" class="stage-line"></div>
                  </div>
                </div>
              </div>
              
              <!-- 部门级别进度详情区域 -->
              <div v-if="stageProgress.department.showDetails" class="progress-details-container">
                <div class="progress-details-card">
                  <div class="progress-details-header">
                    <h3 class="progress-details-title">{{ stageProgress.department.stage.name }} - 进度详情</h3>
                    <button class="btn btn-default" @click="clearStageProgress('department')">×</button>
                  </div>
                  <div class="progress-details-body">
                    <!-- 整体进度 -->
                    <div class="progress-overview">
                      <h4>整体进度</h4>
                      <div class="progress-card">
                        <div class="progress-info">
                          <span class="progress-percentage">{{ stageProgress.department.progress }}%</span>
                          <span class="progress-label">完成度</span>
                        </div>
                        <div class="progress-bar">
                          <div class="progress-fill" :style="{ width: stageProgress.department.progress + '%' }"></div>
                        </div>
                      </div>
                    </div>
                    
                    <!-- 各子任务进度 -->
                    <div class="subtasks-progress">
                      <h4>任务完成度</h4>
                      <div class="subtasks-list">
                        <div v-for="task in stageProgress.department.tasks" :key="task.name" class="subtask-item">
                          <div class="subtask-header">
                            <span class="subtask-name">{{ task.name }}</span>
                            <span class="subtask-percentage">{{ task.progress }}%</span>
                          </div>
                          <div class="progress-bar">
                            <div class="progress-fill" :style="{ width: task.progress + '%', backgroundColor: getTaskColor(task.progress) }"></div>
                          </div>
                          <!-- 任务状态统计 -->
                          <div class="task-stats" style="margin-top: 8px; display: flex; gap: 15px; font-size: 12px;">
                            <span class="stat-item"><span class="completed">已完成:</span> {{ task.completedTasks }}</span>
                            <span class="stat-item"><span class="pending">待处理:</span> {{ task.pendingTasks }}</span>
                            <span class="stat-item"><span class="processing">处理中:</span> {{ task.processingTasks }}</span>
                            <span class="stat-item"><span class="rejected">已拒绝:</span> {{ task.rejectedTasks }}</span>
                            <span class="stat-item"><span class="skipped">已跳过:</span> {{ task.skippedTasks }}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                    
                    <!-- 处理人统计 -->
                    <div class="processors-statistics">
                      <h4>处理人统计</h4>
                      <div class="processors-list">
                        <div v-for="processor in stageProgress.department.processors" :key="processor.userId" class="processor-item">
                          <div class="processor-name">{{ processor.userName }}
                            <span class="processor-id" style="font-size: 12px; color: #8c8c8c; margin-left: 10px;">
                              (用户ID: {{ processor.userId }} | 认证ID: {{ processor.userAuthId }})
                            </span>
                          </div>
                          <div class="processor-stats" style="margin-top: 8px;">
                            <div class="stat-item">
                              <span class="stat-label">任务总数:</span>
                              <span class="stat-value">{{ processor.totalTasks }}</span>
                            </div>
                            <div class="stat-item">
                              <span class="stat-label completed">已完成:</span>
                              <span class="stat-value solved">{{ processor.completedTasks }}</span>
                            </div>
                            <div class="stat-item">
                              <span class="stat-label pending">待处理:</span>
                              <span class="stat-value pending">{{ processor.pendingTasks }}</span>
                            </div>
                            <div class="stat-item">
                              <span class="stat-label processing">处理中:</span>
                              <span class="stat-value processing">{{ processor.processingTasks }}</span>
                            </div>
                          </div>
                          <div class="progress-bar" style="margin-top: 10px; display: flex; height: 8px; background-color: #f0f0f0; border-radius: 4px; overflow: hidden;">
                              <div 
                                class="progress-fill solved" 
                                :style="{
                                  width: processor.totalTasks > 0 ? (processor.completedTasks / processor.totalTasks * 100) + '%' : '0%',
                                  backgroundColor: '#52c41a',
                                  transition: 'width 0.3s ease'
                                }"
                              ></div>
                              <div 
                                class="progress-fill processing" 
                                :style="{
                                  width: processor.totalTasks > 0 ? (processor.processingTasks / processor.totalTasks * 100) + '%' : '0%',
                                  backgroundColor: '#1890ff',
                                  transition: 'width 0.3s ease'
                                }"
                              ></div>
                              <div 
                                class="progress-fill pending" 
                                :style="{
                                  width: processor.totalTasks > 0 ? ((processor.totalTasks - processor.completedTasks - processor.processingTasks) / processor.totalTasks * 100) + '%' : '100%',
                                  backgroundColor: '#faad14',
                                  transition: 'width 0.3s ease'
                                }"
                              ></div>
                            </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 应用结果 -->
          <div v-if="searchForm.application" class="result-section">
            <div class="result-header" @click="toggleResultVisibility('application')">
              <h4>应用: {{ searchForm.application }} <span class="expand-icon">{{ isApplicationExpanded ? '▼' : '▶' }}</span></h4>
            </div>
            <div v-if="isApplicationExpanded" class="result-content">
              <div class="process-flow">
                <h5>应用投产流程</h5>
                <div class="flow-container">
                  <div v-for="(stage, index) in applicationStages" :key="stage.id" class="flow-stage clickable-stage"
                       @click="showStageProgress('application', stage)">
                    <div class="stage-dot" :class="{ 'completed': getStageCompletion('application', stage) === 100 }" :style="{ backgroundColor: getStageColor('application', stage) }"></div>
                    <div class="stage-name">{{ stage.name }}</div>
                    <div v-if="index < applicationStages.length - 1" class="stage-line"></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 版本级别进度详情区域 -->
          <div v-if="stageProgress.version.showDetails" class="progress-details-container">
            <div class="progress-details-card">
              <div class="progress-details-header">
                <h3 class="progress-details-title">{{ stageProgress.version.stage.name }} - 进度详情</h3>
                <button class="btn btn-default" @click="clearStageProgress('version')">×</button>
              </div>
              <div class="progress-details-body">
                <!-- 整体进度 -->
                <div class="progress-overview">
                  <h4>整体进度</h4>
                  <div class="progress-card">
                    <div class="progress-info">
                      <span class="progress-percentage">{{ stageProgress.version.progress }}%</span>
                      <span class="progress-label">完成度</span>
                    </div>
                    <div class="progress-bar">
                      <div class="progress-fill" :style="{ width: stageProgress.version.progress + '%' }"></div>
                    </div>
                  </div>
                </div>
                
                <!-- 各子任务进度 -->
                <div class="subtasks-progress">
                  <h4>任务完成度</h4>
                  <div class="subtasks-list">
                    <div v-for="task in stageProgress.version.tasks" :key="task.name" class="subtask-item">
                      <div class="subtask-header">
                        <span class="subtask-name">{{ task.name }}</span>
                        <span class="subtask-percentage">{{ task.progress }}%</span>
                      </div>
                      <div class="progress-bar">
                        <div class="progress-fill" :style="{ width: task.progress + '%', backgroundColor: getTaskColor(task.progress) }"></div>
                      </div>
                    </div>
                  </div>
                </div>
                
                <!-- 处理人统计 -->
                <div class="processors-statistics">
                  <h4>处理人统计</h4>
                  <div class="processors-list">
                    <div v-for="processor in stageProgress.version.processors" :key="processor.name" class="processor-item">
                      <div class="processor-name">{{ processor.name }}</div>
                      <div class="processor-stats">
                        <div class="stat-item">
                          <span class="stat-label">任务总数:</span>
                          <span class="stat-value">{{ processor.totalTasks }}</span>
                        </div>
                        <div class="stat-item">
                          <span class="stat-label">已解决:</span>
                          <span class="stat-value solved">{{ processor.solvedTasks }}</span>
                        </div>
                        <div class="stat-item">
                          <span class="stat-label">未解决:</span>
                          <span class="stat-value pending">{{ processor.totalTasks - processor.solvedTasks }}</span>
                        </div>
                      </div>
                      <div class="progress-bar" style="margin-top: 10px; display: flex; height: 8px; background-color: #f0f0f0; border-radius: 4px; overflow: hidden;">
                          <div 
                            class="progress-fill solved" 
                            :style="{
                              width: processor.totalTasks > 0 ? (processor.solvedTasks / processor.totalTasks * 100) + '%' : '0%',
                              backgroundColor: '#52c41a',
                              transition: 'width 0.3s ease'
                            }"
                          ></div>
                          <div 
                            class="progress-fill pending" 
                            :style="{
                              width: processor.totalTasks > 0 ? ((processor.totalTasks - processor.solvedTasks) / processor.totalTasks * 100) + '%' : '100%',
                              backgroundColor: '#faad14',
                              transition: 'width 0.3s ease'
                            }"
                          ></div>
                        </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          

          
          <!-- 应用级别进度详情区域 -->
          <div v-if="stageProgress.application.showDetails" class="progress-details-container">
            <div class="progress-details-card">
              <div class="progress-details-header">
                <h3 class="progress-details-title">{{ stageProgress.application.stage.name }} - 进度详情</h3>
                <button class="btn btn-default" @click="clearStageProgress('application')">×</button>
              </div>
              <div class="progress-details-body">
                <!-- 整体进度 -->
                <div class="progress-overview">
                  <h4>整体进度</h4>
                  <div class="progress-card">
                    <div class="progress-info">
                      <span class="progress-percentage">{{ stageProgress.application.progress }}%</span>
                      <span class="progress-label">完成度</span>
                    </div>
                    <div class="progress-bar">
                      <div class="progress-fill" :style="{ width: stageProgress.application.progress + '%' }"></div>
                    </div>
                  </div>
                </div>
                
                <!-- 各子任务进度 -->
                <div class="subtasks-progress">
                  <h4>任务完成度</h4>
                  <div class="subtasks-list">
                    <div v-for="task in stageProgress.application.tasks" :key="task.name" class="subtask-item">
                      <div class="subtask-header">
                        <span class="subtask-name">{{ task.name }}</span>
                        <span class="subtask-percentage">{{ task.progress }}%</span>
                      </div>
                      <div class="progress-bar">
                        <div class="progress-fill" :style="{ width: task.progress + '%', backgroundColor: getTaskColor(task.progress) }"></div>
                      </div>
                      <!-- 任务状态统计 -->
                      <div class="task-stats" style="margin-top: 8px; display: flex; gap: 15px; font-size: 12px;">
                        <span class="stat-item"><span class="completed">已完成:</span> {{ task.completedTasks }}</span>
                        <span class="stat-item"><span class="pending">待处理:</span> {{ task.pendingTasks }}</span>
                        <span class="stat-item"><span class="processing">处理中:</span> {{ task.processingTasks }}</span>
                        <span class="stat-item"><span class="rejected">已拒绝:</span> {{ task.rejectedTasks }}</span>
                        <span class="stat-item"><span class="skipped">已跳过:</span> {{ task.skippedTasks }}</span>
                      </div>
                    </div>
                  </div>
                </div>
                
                <!-- 处理人统计 -->
                <div class="processors-statistics">
                  <h4>处理人统计</h4>
                  <div class="processors-list">
                    <div v-for="processor in stageProgress.application.processors" :key="processor.userId" class="processor-item">
                      <div class="processor-name">{{ processor.userName }}
                        <span class="processor-id" style="font-size: 12px; color: #8c8c8c; margin-left: 10px;">
                          (用户ID: {{ processor.userId }} | 认证ID: {{ processor.userAuthId }})
                        </span>
                      </div>
                      <div class="processor-stats" style="margin-top: 8px;">
                        <div class="stat-item">
                          <span class="stat-label">任务总数:</span>
                          <span class="stat-value">{{ processor.totalTasks }}</span>
                        </div>
                        <div class="stat-item">
                          <span class="stat-label completed">已完成:</span>
                          <span class="stat-value solved">{{ processor.completedTasks }}</span>
                        </div>
                        <div class="stat-item">
                          <span class="stat-label pending">待处理:</span>
                          <span class="stat-value pending">{{ processor.pendingTasks }}</span>
                        </div>
                        <div class="stat-item">
                          <span class="stat-label processing">处理中:</span>
                          <span class="stat-value processing">{{ processor.processingTasks }}</span>
                        </div>
                      </div>
                      <div class="progress-bar" style="margin-top: 10px; display: flex; height: 8px; background-color: #f0f0f0; border-radius: 4px; overflow: hidden;">
                          <div 
                            class="progress-fill solved" 
                            :style="{
                              width: processor.totalTasks > 0 ? (processor.completedTasks / processor.totalTasks * 100) + '%' : '0%',
                              backgroundColor: '#52c41a',
                              transition: 'width 0.3s ease'
                            }"
                          ></div>
                          <div 
                            class="progress-fill processing" 
                            :style="{
                              width: processor.totalTasks > 0 ? (processor.processingTasks / processor.totalTasks * 100) + '%' : '0%',
                              backgroundColor: '#1890ff',
                              transition: 'width 0.3s ease'
                            }"
                          ></div>
                          <div 
                            class="progress-fill pending" 
                            :style="{
                              width: processor.totalTasks > 0 ? ((processor.totalTasks - processor.completedTasks - processor.processingTasks) / processor.totalTasks * 100) + '%' : '100%',
                              backgroundColor: '#faad14',
                              transition: 'width 0.3s ease'
                            }"
                          ></div>
                        </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 新增/编辑阶段模态框 -->
    <div v-if="showStageModal" class="modal" @mousedown="handleModalMouseDown" @mouseup="handleModalMouseUp">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3 class="modal-title">{{ isEditStageMode ? '编辑阶段' : '新建阶段' }}</h3>
          <button class="btn btn-default" @click="closeStageModal">×</button>
        </div>
        <div class="modal-body">
          <div class="form-item">
            <label class="form-label">阶段名称</label>
            <input
              type="text"
              class="input"
              v-model="stageFormData.name"
              placeholder="请输入阶段名称"
              required
            />
            <div v-if="stageNameError" class="error-message">{{ stageNameError }}</div>
          </div>
          <div class="form-item">
            <label class="form-label">描述</label>
            <textarea
              class="input"
              v-model="stageFormData.description"
              placeholder="请输入描述信息"
              rows="3"
            ></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-default" @click="closeStageModal">取消</button>
          <button class="btn btn-primary" @click="saveStage">
            {{ isEditStageMode ? '更新' : '确定' }}
          </button>
        </div>
      </div>
    </div>
    
    <!-- 消息提示容器 -->
    <div ref="messageContainer" class="message-container"></div>
    
    <!-- 确认删除模态框 -->
    <div v-if="showConfirmModal" class="modal-overlay" @click="cancelDelete">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>确认删除</h3>
        </div>
        <div class="modal-body">
          <p>确定要删除该阶段吗？此操作不可撤销。</p>
        </div>
        <div class="modal-footer">
          <button class="btn btn-default" @click="cancelDelete">取消</button>
          <button class="btn btn-danger" @click="deleteStage">确认删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import TopNavigation from '../components/TopNavigation.vue'
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import * as fullProcessSimulationService from '../services/fullProcessSimulationService'
import { departmentService } from '../services/departmentService.js'
import * as workflowService from '../services/workflowService.js'
import taskService from '../services/taskService.js'

// 当前激活的标签页
const activeTab = ref('config')

// 阶段列表数据
const stages = ref([])

// 可选任务类型
const availableTaskTypes = ref([])

// 投产情况汇总数据
const productionSummary = ref({
  totalStages: 0,
  completedStages: 0,
  pendingStages: 0,
  successRate: 0,
  startTime: '',
  estimatedEndTime: '',
  currentStage: '',
  issues: []
})

// 搜索表单数据
const searchForm = ref({
  ecosVersion: '',
  department: '',
  application: ''
})

// 部门列表
const departments = ref([])

// ECOS版本列表
const ecosVersions = ref([])

// 应用列表
const applications = ref([])

// 搜索结果状态
const showSearchResults = ref(false)
const searchResults = ref({ stages: [] })

// 展开/收起状态
const isEcosExpanded = ref(false)
const isDepartmentExpanded = ref(false)
const isApplicationExpanded = ref(false)

// 不同级别的流程数据
const versionStages = ref([])
const departmentStages = ref([])
const applicationStages = ref([])

// 模态框相关状态
const showStageModal = ref(false)
const isEditStageMode = ref(false)
const currentStageId = ref(null)
const stageFormData = ref({ name: '', description: '' })
const stageNameError = ref('')

// 拖拽相关状态
const dragState = ref({
  isDragging: false,
  draggingId: null,
  targetId: null
})

// 消息容器引用
const messageContainer = ref(null)

// 获取工作流数据并设置为阶段数据
const fetchWorkflows = async () => {
  try {
    // 1. 获取所有工作流（阶段）数据
    const response = await workflowService.getWorkflows()
    // 转换工作流数据为阶段数据格式
    let workflowsData = response.data
      .map(workflow => ({
        id: workflow.id,
        name: workflow.flowName,
        order: workflow.workflowOrder,
        description: workflow.description,
        selectedTasks: [],
        createdAt: workflow.createdAt,
        updatedAt: workflow.updatedAt
      }))
      .sort((a, b) => a.order - b.order)
    
    // 2. 获取所有任务类型关系列表（优化为一次性获取所有任务，然后根据workflowId分配）
    try {
      // 确保availableTaskTypes已经加载
      if (availableTaskTypes.value.length === 0) {
        await fetchAvailableTaskTypes()
      }
      
      // 获取所有工作流的任务分配信息
      const allTasksResponse = await workflowService.getWorkflowTaskTypes()
      
      if (allTasksResponse.data && Array.isArray(allTasksResponse.data)) {
        // 3. 根据workflowId将任务分配给对应的阶段
        allTasksResponse.data.forEach(task => {
          // 查找对应的阶段（阶段的id需要与任务的workflowId相同）
          const stage = workflowsData.find(stage => stage.id === task.workflowId)
          if (stage) {
            // 查找匹配的任务类型名称
            const matchingTaskType = availableTaskTypes.value.find(t => t.id === task.taskTypeId)
            const taskName = matchingTaskType?.taskName || task.taskTypeName || task.taskTypeName
            
            // 确保任务名称不为空且不重复添加
            if (taskName && !stage.selectedTasks.includes(taskName)) {
              stage.selectedTasks.push(taskName)
            }
          }
        })
      }
    } catch (allTasksError) {
      console.warn('获取所有工作流任务分配失败，尝试为每个工作流单独获取:', allTasksError)
      
      // 备用方案：为每个工作流单独获取任务分配信息
      for (let i = 0; i < workflowsData.length; i++) {
        try {
          const workflowId = workflowsData[i].id
          const tasksResponse = await workflowService.getWorkflowTaskTypes(workflowId)
          
          // 确保availableTaskTypes已经加载
          if (availableTaskTypes.value.length === 0) {
            await fetchAvailableTaskTypes()
          }
          
          // 提取任务类型名称，确保与availableTaskTypes中的taskName匹配
          if (tasksResponse.data && Array.isArray(tasksResponse.data)) {
            workflowsData[i].selectedTasks = tasksResponse.data
              .map(task => {
                // 查找匹配的任务类型名称
                const matchingTaskType = availableTaskTypes.value.find(t => t.id === task.taskTypeId)
                return matchingTaskType?.taskName || task.taskTypeName || task
              })
              .filter(Boolean) // 过滤掉无效值
          }
        } catch (taskError) {
          console.warn(`获取工作流ID为${workflowsData[i].id}的任务分配失败:`, taskError)
          // 继续处理下一个工作流，不中断整体流程
          workflowsData[i].selectedTasks = []
        }
      }
    }
    
    // 设置最终的阶段数据
    stages.value = workflowsData
    
    console.log('获取工作流数据并设置为阶段数据成功，包含任务分配信息:', stages.value)
  } catch (error) {
    showMessage('获取工作流数据失败: ' + (error.message || '未知错误'), 'error')
    console.error('Failed to fetch workflows:', error)
  }
}

// 监听标签页切换，当切换到统计配置界面时获取工作流数据
watch(activeTab, async (newTab) => {
  if (newTab === 'config') {
    // 确保任务类型先加载
    await fetchAvailableTaskTypes()
    // 然后获取工作流数据
    await fetchWorkflows()
  }
})

// 获取可选任务类型
const fetchAvailableTaskTypes = async () => {
  try {
    availableTaskTypes.value = await fullProcessSimulationService.getAvailableTaskTypes()
    console.log('获取可选任务类型成功:', availableTaskTypes.value)
  } catch (error) {
    showMessage('获取任务类型失败: ' + (error.message || '未知错误'), 'error')
    console.error('Failed to fetch task types:', error)
  }
}

// 获取投产情况汇总
const fetchProductionSummary = async () => {
  try {
    const response = await fullProcessSimulationService.getProductionSummary()
    productionSummary.value = response.data
  } catch (error) {
    showMessage('获取投产情况汇总失败: ' + (error.message || '未知错误'), 'error')
    console.error('Failed to fetch production summary:', error)
  }
}

// 获取部门列表
const fetchDepartments = async (ecosVersion = searchForm.value.ecosVersion) => {
  try {
    const response = await taskService.getDepartments(ecosVersion)
    // 处理API返回的数据格式，将dep字段映射为显示所需的格式
    departments.value = (response.data || []).map(item => ({
      id: item.dep, // 使用部门名称作为唯一标识
      dep: item.dep // 保留原始的dep字段
    }))
  } catch (error) {
    showMessage('获取部门列表失败: ' + (error.message || '未知错误'), 'error')
    console.error('Failed to fetch departments:', error)
  }
}

// 获取应用列表
const fetchApplications = async (version = searchForm.value.ecosVersion, department = searchForm.value.department) => {
  try {
    const response = await taskService.getApplications(version, department)
    // 处理API返回的数据格式，只提取应用名称
    applications.value = (response.data || []).map(item => item.app || item)
  } catch (error) {
    showMessage('获取应用列表失败: ' + (error.message || '未知错误'), 'error')
    console.error('Failed to fetch applications:', error)
  }
}

// 显示新增阶段模态框
const showAddStageModal = () => {
  isEditStageMode.value = false
  currentStageId.value = null
  stageFormData.value = { name: '', description: '' }
  stageNameError.value = ''
  showStageModal.value = true
}

// 显示编辑阶段模态框
const showEditStageModal = (stage) => {
  isEditStageMode.value = true
  currentStageId.value = stage.id
  stageFormData.value = { name: stage.name, description: stage.description || '' }
  stageNameError.value = ''
  showStageModal.value = true
}

// 标记是否正在进行文本选择
let isSelectingText = false

// 处理模态框鼠标按下事件
const handleModalMouseDown = () => {
  isSelectingText = false
}

// 处理模态框鼠标松开事件
const handleModalMouseUp = (event) => {
  // 检查是否有选中的文本
  if (document.getSelection().toString().length > 0) {
    isSelectingText = true
    return
  }
  
  // 如果不是在选择文本，则关闭模态框
  const target = event.target
  if (!target.closest('.modal-content')) {
    closeStageModal()
  }
}

// 关闭阶段模态框
const closeStageModal = () => {
  // 如果正在进行文本选择，则不关闭弹窗
  if (isSelectingText) {
    return
  }
  
  showStageModal.value = false
  stageNameError.value = ''
  isSelectingText = false
}

// 保存阶段
const saveStage = async () => {
  // 验证阶段名称
  if (!stageFormData.value.name.trim()) {
    stageNameError.value = '阶段名称不能为空'
    return
  }
  
  // 检查阶段名称是否已存在（编辑时排除当前阶段）
  const isNameExists = stages.value.some(stage => 
    stage.name === stageFormData.value.name && stage.id !== currentStageId.value
  )
  
  if (isNameExists) {
    stageNameError.value = '阶段名称已存在'
    return
  }
  
  try {
    if (isEditStageMode.value) {
      // 更新阶段
      const stageToUpdate = stages.value.find(s => s.id === currentStageId.value)
      await workflowService.updateWorkflow(currentStageId.value, {
        id: currentStageId.value,
        flowName: stageFormData.value.name,
        description: stageFormData.value.description,
        workflowOrder: stageToUpdate.order,
        createdAt: stageToUpdate.createdAt,
        updatedAt: new Date().toISOString()
      })
      showMessage('阶段更新成功', 'success')
    } else {
      // 新增阶段
      const newOrder = stages.value.length + 1
      await workflowService.createWorkflow({
        id: 0,
        flowName: stageFormData.value.name,
        description: stageFormData.value.description,
        workflowOrder: newOrder,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      })
      showMessage('阶段创建成功', 'success')
    }
    
    // 重新获取阶段数据
    await fetchWorkflows()
    closeStageModal()
  } catch (error) {
    showMessage(`操作失败: ${error.message || '未知错误'}`, 'error')
    console.error('Failed to save stage:', error)
  }
}

// 确认删除模态框状态
const showConfirmModal = ref(false)
const stageToDelete = ref(null)

// 显示确认删除模态框
const showDeleteConfirmModal = (id) => {
  stageToDelete.value = id
  showConfirmModal.value = true
}

// 删除阶段
const deleteStage = async () => {
  if (!stageToDelete.value) return
  
  try {
    await workflowService.deleteWorkflow(stageToDelete.value)
    
    showMessage('阶段删除成功', 'success')
    await fetchWorkflows()
    showConfirmModal.value = false
    stageToDelete.value = null
  } catch (error) {
    showMessage(`删除失败: ${error.message || '未知错误'}`, 'error')
    console.error('Failed to delete stage:', error)
  }
}

// 取消删除
const cancelDelete = () => {
  showConfirmModal.value = false
  stageToDelete.value = null
}

// 上移阶段
const moveStageUp = async (stageOrder) => {
  const stageToMove = stages.value.find(stage => stage.order === stageOrder)
  if (!stageToMove || stageOrder <= 1) return
  
  try {
    // 找到上一个阶段
    const prevStage = stages.value.find(stage => stage.order === stageOrder - 1)
    
    if (prevStage) {
      // 避免唯一约束冲突的三步更新法
      // 1. 先将当前阶段的order设置为一个临时值（负数值）
      await workflowService.updateWorkflow(stageToMove.id, {
        id: stageToMove.id,
        flowName: stageToMove.name,
        description: stageToMove.description,
        workflowOrder: -stageOrder, // 使用负数值作为临时值
        createdAt: stageToMove.createdAt,
        updatedAt: stageToMove.updatedAt
      })
      
      // 2. 然后将上一个阶段的order设置为当前阶段原来的order
      await workflowService.updateWorkflow(prevStage.id, {
        id: prevStage.id,
        flowName: prevStage.name,
        description: prevStage.description,
        workflowOrder: stageOrder,
        createdAt: prevStage.createdAt,
        updatedAt: prevStage.updatedAt
      })
      
      // 3. 最后将当前阶段的order设置为上一个阶段原来的order
      await workflowService.updateWorkflow(stageToMove.id, {
        id: stageToMove.id,
        flowName: stageToMove.name,
        description: stageToMove.description,
        workflowOrder: stageOrder - 1,
        createdAt: stageToMove.createdAt,
        updatedAt: stageToMove.updatedAt
      })
      
      showMessage('阶段顺序已调整', 'success')
      await fetchWorkflows()
    }
  } catch (error) {
    showMessage(`调整失败: ${error.message || '未知错误'}`, 'error')
    console.error('Failed to move stage up:', error)
  }
}

// 下移阶段
const moveStageDown = async (stageOrder) => {
  const stageToMove = stages.value.find(stage => stage.order === stageOrder)
  if (!stageToMove || stageOrder >= stages.value.length) return
  
  try {
    // 找到下一个阶段
    const nextStage = stages.value.find(stage => stage.order === stageOrder + 1)
    
    if (nextStage) {
      // 避免唯一约束冲突的三步更新法
      // 1. 先将当前阶段的order设置为一个临时值（负数值）
      await workflowService.updateWorkflow(stageToMove.id, {
        id: stageToMove.id,
        flowName: stageToMove.name,
        description: stageToMove.description,
        workflowOrder: -stageOrder, // 使用负数值作为临时值
        createdAt: stageToMove.createdAt,
        updatedAt: stageToMove.updatedAt
      })
      
      // 2. 然后将下一个阶段的order设置为当前阶段原来的order
      await workflowService.updateWorkflow(nextStage.id, {
        id: nextStage.id,
        flowName: nextStage.name,
        description: nextStage.description,
        workflowOrder: stageOrder,
        createdAt: nextStage.createdAt,
        updatedAt: nextStage.updatedAt
      })
      
      // 3. 最后将当前阶段的order设置为下一个阶段原来的order
      await workflowService.updateWorkflow(stageToMove.id, {
        id: stageToMove.id,
        flowName: stageToMove.name,
        description: stageToMove.description,
        workflowOrder: stageOrder + 1,
        createdAt: stageToMove.createdAt,
        updatedAt: stageToMove.updatedAt
      })
      
      showMessage('阶段顺序已调整', 'success')
      await fetchWorkflows()
    }
  } catch (error) {
    showMessage(`调整失败: ${error.message || '未知错误'}`, 'error')
    console.error('Failed to move stage down:', error)
  }
}

// 切换任务选择
const toggleTask = async (stageId, taskName) => {
  try {
    const stage = stages.value.find(s => s.id === stageId)
    const updatedTasks = [...stage.selectedTasks]
    
    // 检查任务是否已存在
    const taskIndex = updatedTasks.indexOf(taskName)
    if (taskIndex === -1) {
      // 添加任务
      updatedTasks.push(taskName)
      
      // 确保availableTaskTypes已经加载
      if (availableTaskTypes.value.length === 0) {
        await fetchAvailableTaskTypes()
      }
      
      // 获取任务类型信息
      const taskTypeInfo = availableTaskTypes.value.find(task => task.taskName === taskName)
      
      if (!taskTypeInfo) {
        console.warn(`未找到任务类型信息: ${taskName}`)
        showMessage(`未找到任务类型信息: ${taskName}`, 'warning')
        stage.selectedTasks = updatedTasks
        return
      }
      
      // 调用接口保存到后端
      try {
        // 准备请求参数，确保使用正确的任务类型ID和数据源ID
        // 确保taskTypeId有有效值，防止数据库约束错误
        const taskTypeId = taskTypeInfo.id || taskTypeInfo.taskTypeId || 0;
        if (!taskTypeId) {
          console.warn(`任务类型ID无效: ${taskName}`);
          showMessage(`任务类型ID无效，无法添加任务: ${taskName}`, 'warning');
          stage.selectedTasks = updatedTasks;
          return;
        }
        
        const taskData = {
          workflowId: stageId,
          workflowName: stage.name,
          taskTypeId: taskTypeId, // 使用确保有效的任务类型ID
          taskTypeName: taskName,
          datasourceId: taskTypeInfo.dataSourceId || 1, // 使用任务类型中的数据源ID，如果不存在则使用默认值
          taskOrder: 1 // 使用默认值
        }
        
        await workflowService.createWorkflowTaskType(taskData)
        console.log('成功调用API保存任务类型关系:', taskData)
        showMessage(`成功添加任务: ${taskName}`, 'success')
      } catch (apiError) {
        console.warn('调用API失败，但仍会更新本地状态:', apiError)
        // 即使API调用失败，我们仍然更新本地状态
        showMessage(`任务添加失败: ${apiError.message || '未知错误'}`, 'error')
      }
    } else {
      // 移除任务
      updatedTasks.splice(taskIndex, 1)
      
      // 调用API删除任务类型关系
      try {
        // 确保availableTaskTypes已经加载
        if (availableTaskTypes.value.length === 0) {
          await fetchAvailableTaskTypes()
        }
        
        // 获取任务类型信息，查找taskTypeId
        let taskTypeInfo = null
        // 尝试匹配name字段
        taskTypeInfo = availableTaskTypes.value.find(task => task.name === taskName)
        // 如果没找到，尝试匹配taskName字段
        if (!taskTypeInfo) {
          taskTypeInfo = availableTaskTypes.value.find(task => task.taskName === taskName)
        }
        // 如果还是没找到，尝试匹配typeName字段
        if (!taskTypeInfo) {
          taskTypeInfo = availableTaskTypes.value.find(task => task.typeName === taskName)
        }
        
        // 获取任务类型ID
        let taskTypeId = null
        if (taskTypeInfo) {
          taskTypeId = taskTypeInfo.id || taskTypeInfo.taskTypeId || taskTypeInfo.typeId
          console.log(`找到任务类型ID: ${taskTypeId}`)
        }
        
        if (taskTypeId && !isNaN(parseInt(taskTypeId))) {
          // 调用用户指定格式的API接口：http://192.168.198.213:8081/api/workflow-task-types/workflow/6/task-type/{taskTypeId}
          await workflowService.deleteWorkflowTaskType(6, parseInt(taskTypeId))
          console.log(`成功调用API删除工作流ID为6的任务类型ID为${taskTypeId}的关系`)
        } else {
          console.warn(`未找到有效的任务类型ID: ${taskName}`)
          showMessage(`无法删除任务，未找到对应的任务类型ID: ${taskName}`, 'warning')
        }
      } catch (apiError) {
        console.warn('调用API删除任务失败，但仍会更新本地状态:', apiError)
        showMessage(`任务删除API调用失败: ${apiError.message || '未知错误'}`, 'warning')
      }
      
      showMessage(`成功移除任务: ${taskName}`, 'success')
    }
    
    // 更新本地状态
    stage.selectedTasks = updatedTasks
  } catch (error) {
    showMessage(`任务更新失败: ${error.message || '未知错误'}`, 'error')
    console.error('Failed to toggle task:', error)
  }
}

// 移除任务
const removeTask = async (stageId, taskName) => {
  try {
    const stage = stages.value.find(s => s.id === stageId)
    const updatedTasks = stage.selectedTasks.filter(t => t !== taskName)
    
    // 调用API删除任务类型关系
    try {
      // 确保availableTaskTypes已经加载
      if (availableTaskTypes.value.length === 0) {
        await fetchAvailableTaskTypes()
      }
      
      // 获取任务类型信息，查找taskTypeId - 修改为更通用的字段匹配
      console.log('availableTaskTypes:', availableTaskTypes.value)
      let taskTypeInfo = null
      // 首先尝试匹配name字段
      taskTypeInfo = availableTaskTypes.value.find(task => task.name === taskName)
      // 如果没找到，尝试匹配taskName字段
      if (!taskTypeInfo) {
        taskTypeInfo = availableTaskTypes.value.find(task => task.taskName === taskName)
      }
      // 如果还是没找到，尝试匹配typeName字段
      if (!taskTypeInfo) {
        taskTypeInfo = availableTaskTypes.value.find(task => task.typeName === taskName)
      }
      
      // 更智能的字段匹配 - 尝试所有可能的ID字段
      let taskTypeId = null
      if (taskTypeInfo) {
        // 尝试不同的ID字段名
        taskTypeId = taskTypeInfo.id || taskTypeInfo.taskTypeId || taskTypeInfo.typeId
        console.log(`找到任务类型ID: ${taskTypeId}`)
      }
      
      if (taskTypeId && !isNaN(parseInt(taskTypeId))) {
        // 调用新的删除接口，确保传递数字类型的ID
        await workflowService.deleteWorkflowTaskType(stageId, parseInt(taskTypeId))
        console.log(`成功调用API删除工作流ID为${stageId}的任务类型ID为${taskTypeId}的关系`)
      } else {
        console.warn(`未找到有效的任务类型ID: ${taskName}`)
        showMessage(`无法删除任务，未找到对应的任务类型ID: ${taskName}`, 'warning')
      }
    } catch (apiError) {
      console.warn('调用API删除任务失败，但仍会更新本地状态:', apiError)
      showMessage(`任务删除API调用失败: ${apiError.message || '未知错误'}`, 'warning')
    }
    
    // 更新本地状态
    stage.selectedTasks = updatedTasks
    showMessage(`成功移除任务: ${taskName}`, 'success')
  } catch (error) {
    showMessage(`任务移除失败: ${error.message || '未知错误'}`, 'error')
    console.error('Failed to remove task:', error)
  }
}

// 拖拽开始
const handleDragStart = (event, stageId) => {
  dragState.value.isDragging = true
  dragState.value.draggingId = stageId
  event.dataTransfer.effectAllowed = 'move'
}

// 拖拽经过
const handleDragOver = (event, stageId) => {
  event.preventDefault()
  event.dataTransfer.dropEffect = 'move'
  dragState.value.targetId = stageId
}

// 拖拽释放
const handleDrop = async (targetId) => {
  event.preventDefault()
  
  if (dragState.value.draggingId === targetId || !dragState.value.isDragging) {
    dragState.value.isDragging = false
    dragState.value.draggingId = null
    dragState.value.targetId = null
    return
  }
  
  try {
    const draggedStage = stages.value.find(s => s.id === dragState.value.draggingId)
    const targetStage = stages.value.find(s => s.id === targetId)
    
    // 保存原始顺序
    const draggedOrder = draggedStage.order
    const targetOrder = targetStage.order
    
    // 更新拖拽的阶段
    await workflowService.updateWorkflow(draggedStage.id, {
      flowName: draggedStage.name,
      description: draggedStage.description,
      workflowOrder: targetOrder
    })
    
    // 更新目标阶段
    await workflowService.updateWorkflow(targetStage.id, {
      flowName: targetStage.name,
      description: targetStage.description,
      workflowOrder: draggedOrder
    })
    
    showMessage('阶段顺序已调整', 'success')
    await fetchWorkflows()
  } catch (error) {
    showMessage(`调整失败: ${error.message || '未知错误'}`, 'error')
    console.error('Failed to drop stage:', error)
  } finally {
    dragState.value.isDragging = false
    dragState.value.draggingId = null
    dragState.value.targetId = null
  }
}

// 执行搜索
const performSearch = async () => {
  try {
    // 在实际应用中，这里应该调用API获取搜索结果
    // 这里使用模拟数据
    showSearchResults.value = true
    
    // 设置所有级别的数据为相同的完整阶段列表
    versionStages.value = [...stages.value] // 版本级别的流程数据
    departmentStages.value = [...stages.value] // 部门级别的流程数据
    applicationStages.value = [...stages.value] // 应用级别的流程数据
    
    // 生成模拟的进度数据
    generateMockProgressData()
    
    // 设置默认展开/收起状态
    isEcosExpanded.value = false
    isDepartmentExpanded.value = false
    isApplicationExpanded.value = false
    
    // 只有最具体的结果默认展开
    if (searchForm.value.application) {
      isApplicationExpanded.value = true
    } else if (searchForm.value.department) {
      isDepartmentExpanded.value = true
    } else if (searchForm.value.ecosVersion) {
      isEcosExpanded.value = true
    }
    
    showMessage('搜索成功', 'success')
  } catch (error) {
    showMessage('搜索失败: ' + (error.message || '未知错误'), 'error')
    console.error('Failed to perform search:', error)
  }
}

// 生成模拟的进度数据
const generateMockProgressData = () => {
  // 重置进度数据
  stageProgressData.value = {
    version: {},
    department: {},
    application: {}
  }
  
  // 为版本级别生成进度数据
  versionStages.value.forEach((stage, index) => {
    const progress = Math.min(100, index * 30 + Math.floor(Math.random() * 20))
    stageProgressData.value.version[stage.id] = {
      progress,
      tasks: getMockTasks(stage.selectedTasks, progress),
      processors: getMockProcessors()
    }
  })
  
  // 为部门级别生成进度数据
  departmentStages.value.forEach((stage, index) => {
    const progress = Math.min(100, index * 25 + Math.floor(Math.random() * 25))
    stageProgressData.value.department[stage.id] = {
      progress,
      tasks: getMockTasks(stage.selectedTasks, progress),
      processors: getMockProcessors()
    }
  })
  
  // 为应用级别生成进度数据
  applicationStages.value.forEach((stage, index) => {
    const progress = Math.min(100, index * 40 + Math.floor(Math.random() * 30))
    stageProgressData.value.application[stage.id] = {
      progress,
      tasks: getMockTasks(stage.selectedTasks, progress),
      processors: getMockProcessors()
    }
  })
}

// 获取模拟任务数据
const getMockTasks = (selectedTasks, stageProgress) => {
  const tasks = selectedTasks.length > 0 ? selectedTasks : ['变量审核', '环境准备', '测试验证']
  return tasks.map(task => ({
    name: task,
    progress: Math.min(100, stageProgress - 10 + Math.floor(Math.random() * 20))
  }))
}

// 获取模拟处理人数据
const getMockProcessors = () => {
  const processors = ['张三', '李四', '王五', '赵六']
  return processors.map(name => {
    const totalTasks = Math.floor(Math.random() * 10) + 1
    const solvedTasks = Math.floor(Math.random() * (totalTasks + 1))
    return {
      name,
      totalTasks,
      solvedTasks
    }
  })
}

// ECOS版本变化时的处理
const onEcosVersionChange = async () => {
  // 重置部门和应用选择
  searchForm.value.department = ''
  searchForm.value.application = ''
  
  // 如果选择了ECOS版本，重新获取部门数据
  if (searchForm.value.ecosVersion) {
    await fetchDepartments()
  }
}

// 部门变化时的处理
const onDepartmentChange = async () => {
  // 重置应用选择
  if (!searchForm.value.department) {
    searchForm.value.application = ''
  } else {
    // 如果选择了部门，获取应用列表
    await fetchApplications()
  }
}

// 切换结果的展开/收起状态
const toggleResultVisibility = (type) => {
  if (type === 'ecos') {
    isEcosExpanded.value = !isEcosExpanded.value
  } else if (type === 'department') {
    isDepartmentExpanded.value = !isDepartmentExpanded.value
  } else if (type === 'application') {
    isApplicationExpanded.value = !isApplicationExpanded.value
  }
}

// 显示消息提示函数
const showMessage = (message, type = 'info') => {
  // 创建消息元素
  const msgElement = document.createElement('div')
  msgElement.className = `message message-${type} show`
  msgElement.textContent = message
  
  // 添加到消息容器
  if (messageContainer.value) {
    messageContainer.value.appendChild(msgElement)
    
    // 3秒后移除
    setTimeout(() => {
      msgElement.classList.remove('show')
      setTimeout(() => {
        if (messageContainer.value && messageContainer.value.contains(msgElement)) {
          messageContainer.value.removeChild(msgElement)
        }
      }, 300)
    }, 3000)
  }
}

// 模拟的阶段进度数据（用于UI渲染阶段点）
const stageProgressData = ref({
  version: {},
  department: {},
  application: {}
})

// 为每个级别创建独立的进度详情存储（用于显示详细进度信息）
const stageProgress = ref({
  version: {
    stage: {},
    progress: 0,
    tasks: [],
    processors: [],
    showDetails: false
  },
  department: {
    stage: {},
    progress: 0,
    tasks: [],
    processors: [],
    showDetails: false
  },
  application: {
    stage: {},
    progress: 0,
    tasks: [],
    processors: [],
    showDetails: false
  }
})

// 显示阶段进度详情
const showStageProgress = async (level, stage) => {
  try {
    // 显示加载状态
    showMessage('正在加载统计数据...', 'info')
    
    // 根据不同级别构建对应的筛选条件对象
    // 按照需求，每个级别只使用自己的筛选条件
    const filters = {};
    if (level === 'version') {
      // 版本级别：只使用ecos版本筛选
      filters.version = searchForm.value.ecosVersion;
    } else if (level === 'department') {
      // 部门级别：只使用部门筛选
      filters.dep = searchForm.value.department;
    } else if (level === 'application') {
      // 应用级别：只使用应用名称筛选
      filters.app = searchForm.value.application;
    }
    
    // 调用新接口获取工作流统计数据
    const response = await workflowService.getWorkflowStatistics(stage.id, filters)
    const statisticsData = response.data || []
    
    console.log('获取阶段统计数据成功:', statisticsData)
    
    // 设置当前级别对应的阶段信息
    stageProgress.value[level].stage = stage
    
    // 计算整体进度
    if (statisticsData.length > 0) {
      const totalTasks = statisticsData.reduce((sum, task) => sum + task.totalTasks, 0)
      const completedTasks = statisticsData.reduce((sum, task) => sum + task.completedTasks, 0)
      stageProgress.value[level].progress = totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0
      
      // 处理任务完成度数据，保留所有状态的任务数量
      stageProgress.value[level].tasks = statisticsData.map(task => ({
        name: task.taskTypeName,
        progress: task.totalTasks > 0 ? Math.round((task.completedTasks / task.totalTasks) * 100) : 0,
        totalTasks: task.totalTasks,
        completedTasks: task.completedTasks,
        pendingTasks: task.pendingTasks,
        processingTasks: task.processingTasks,
        rejectedTasks: task.rejectedTasks,
        skippedTasks: task.skippedTasks
      }))
      
      // 处理处理人统计数据，保留更多详细信息
      const processorMap = new Map()
      statisticsData.forEach(task => {
        if (task.approverStatistics && Array.isArray(task.approverStatistics)) {
          task.approverStatistics.forEach(approver => {
            const existing = processorMap.get(approver.userId) || {
              userId: approver.userId,
              userName: approver.userName,
              userAuthId: approver.userAuthId,
              totalTasks: 0,
              completedTasks: 0,
              pendingTasks: 0,
              processingTasks: 0
            }
            processorMap.set(approver.userId, {
              userId: approver.userId,
              userName: approver.userName,
              userAuthId: approver.userAuthId,
              totalTasks: existing.totalTasks + (approver.totalTasks || 0),
              completedTasks: existing.completedTasks + (approver.completedTasks || 0),
              pendingTasks: existing.pendingTasks + (approver.pendingTasks || 0),
              processingTasks: existing.processingTasks + (approver.processingTasks || 0)
            })
          })
        }
      })
      stageProgress.value[level].processors = Array.from(processorMap.values())
      
      // 显示该级别的详情
      stageProgress.value[level].showDetails = true
      
      showMessage('统计数据加载成功', 'success')
    } else {
      // 没有数据时的默认值
      stageProgress.value[level].progress = 0
      stageProgress.value[level].tasks = []
      stageProgress.value[level].processors = []
      stageProgress.value[level].showDetails = true
      showMessage('当前阶段暂无统计数据', 'info')
    }
  } catch (error) {
    console.error('获取阶段统计数据失败:', error)
    showMessage('获取统计数据失败: ' + (error.message || '未知错误'), 'error')
    // 设置默认值，避免界面空白
    stageProgress.value[level].progress = 0
    stageProgress.value[level].tasks = []
    stageProgress.value[level].processors = []
    stageProgress.value[level].showDetails = true
  }
}

// 清除指定级别的阶段进度详情
const clearStageProgress = (level) => {
  if (level) {
    stageProgress.value[level].stage = {}
    stageProgress.value[level].progress = 0
    stageProgress.value[level].tasks = []
    stageProgress.value[level].processors = []
    stageProgress.value[level].showDetails = false
  } else {
    // 清除所有级别的进度详情
    stageProgress.value.version.showDetails = false
    stageProgress.value.department.showDetails = false
    stageProgress.value.application.showDetails = false
  }
}

// 关闭阶段进度详情模态框 - 保留以确保兼容性
const closeProgressModal = () => {
  clearStageProgress()
}

// 获取阶段颜色
const getStageColor = (level, stage) => {
  const completion = getStageCompletion(level, stage)
  if (completion >= 100) return '#52c41a'
  if (completion >= 50) return '#1890ff'
  return '#faad14'
}

// 获取阶段完成度
const getStageCompletion = (level, stage) => {
  const progressData = stageProgressData.value[level]?.[stage.id]
  return progressData?.progress || 0
}

// 获取任务颜色
const getTaskColor = (progress) => {
  if (progress >= 100) return '#52c41a'
  if (progress >= 50) return '#1890ff'
  return '#faad14'
}


// 获取ECOS版本列表
const fetchEcosVersions = async () => {
  try {
    const response = await taskService.getEcosVersions()
    // 处理版本数据，只显示'ECOS Vx.x.x'格式的版本号部分
    ecosVersions.value = (response.data || []).map(item => {
      // 检查数据结构，确保能正确提取版本号
      const versionStr = typeof item === 'object' && item.version ? item.version : String(item);
      // 检查版本字符串中是否包含'ECOS'关键字
      if (versionStr.includes('ECOS')) {
        // 提取'ECOS V'开头和版本号部分
        const match = versionStr.match(/ECOS V\d+\.\d+\.\d+/i);
        if (match) {
          return match[0]; // 返回匹配到的部分
        }
      }
      return versionStr; // 如果没有匹配到特定格式，则返回原始版本字符串
    })
  } catch (error) {
    showMessage(`获取ECOS版本失败: ${error.message || '未知错误'}`, 'error')
    console.error('Failed to fetch ECOS versions:', error)
  }
}

// 组件挂载时初始化数据
onMounted(async () => {
  await fetchAvailableTaskTypes()
  await fetchProductionSummary()
  await fetchEcosVersions()
  
  // 初始时如果是统计配置界面，获取工作流数据
  if (activeTab.value === 'config') {
    await fetchWorkflows()
  }
})

// 格式化日期时间
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}
</script>

<style scoped>
/* 基础样式 */
.route-simulation {
  width: 100%;
  padding: 20px;
}

/* 标签页导航 */
.tabs {
  display: flex;
  margin-bottom: 20px;
  border-bottom: 2px solid var(--border-base);
}

.tab-button {
  padding: 12px 24px;
  background: transparent;
  border: none;
  cursor: pointer;
  font-size: var(--font-size-md);
  font-weight: 500;
  color: var(--text-secondary);
  transition: all 0.3s ease;
  position: relative;
  margin-right: 10px;
}

.tab-button:hover {
  color: var(--primary-color);
}

.tab-button.active {
  color: var(--primary-color);
}

.tab-button.active::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: var(--primary-color);
}

/* 标签页内容 */
  .tab-content {
    animation: fadeIn 0.3s ease;
  }
  
  /* 点击阶段节点样式 */
  .clickable-stage {
    cursor: pointer;
    transition: transform 0.2s ease, filter 0.2s ease;
  }
  
  .clickable-stage:hover {
    transform: translateY(-2px);
    filter: brightness(1.05);
  }
  
  .stage-dot.completed {
    box-shadow: 0 0 0 2px #52c41a;
  }
  
  /* 进度详情区域样式 */
  .progress-details-container {
    margin-top: 20px;
    animation: fadeIn 0.3s ease;
  }
  
  .progress-details-card {
    background: #fff;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    border: 1px solid #f0f0f0;
  }
  
  .progress-details-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 12px;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .progress-details-title {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #262626;
  }
  
  .progress-details-header button {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    color: #8c8c8c;
    padding: 0;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .progress-details-header button:hover {
    color: #595959;
  }
  
  .progress-details-body {
    padding: 10px 0;
  }
  
  /* 进度卡片样式 */
  .progress-overview, .subtasks-progress, .processors-statistics {
    margin-bottom: 24px;
  }
  
  .progress-overview h4, .subtasks-progress h4, .processors-statistics h4 {
    margin: 0 0 12px 0;
    font-size: 16px;
    font-weight: 600;
    color: #262626;
  }
  
  .progress-card {
    background: #fafafa;
    border-radius: 6px;
    padding: 16px;
    display: flex;
    align-items: center;
    gap: 16px;
  }
  
  .progress-info {
    text-align: center;
  }
  
  .progress-percentage {
    display: block;
    font-size: 24px;
    font-weight: 700;
    color: #262626;
  }
  
  .progress-label {
    display: block;
    font-size: 12px;
    color: #8c8c8c;
    margin-top: 4px;
  }
  
  .progress-bar {
    flex: 1;
    height: 8px;
    background: #f0f0f0;
    border-radius: 4px;
    overflow: hidden;
  }
  
  .progress-fill {
    height: 100%;
    background: #1890ff;
    transition: width 0.3s ease;
  }
  
  /* 子任务列表样式 */
  .subtasks-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
  
  .subtask-item {
    padding: 12px;
    background: #fafafa;
    border-radius: 6px;
  }
  
  .subtask-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
  }
  
  .subtask-name {
    font-weight: 500;
    color: #262626;
  }
  
  .subtask-percentage {
    font-size: 14px;
    color: #595959;
  }
  
  /* 处理人统计列表样式 */
  .processors-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
  
  .processor-item {
    padding: 12px;
    background: #fafafa;
    border-radius: 6px;
  }
  
  .processor-name {
    font-weight: 500;
    color: #262626;
    margin-bottom: 8px;
  }
  
  .processor-stats {
    display: flex;
    gap: 24px;
  }
  
  .stat-item {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  
  .stat-label {
    font-size: 12px;
    color: #8c8c8c;
    margin-bottom: 4px;
  }
  
  .stat-value {
    font-size: 16px;
    font-weight: 600;
    color: #262626;
  }
  
  .stat-value.solved {
    color: #52c41a;
  }
  
  .stat-value.pending {
    color: #faad14;
  }
  
  /* 按钮样式 */
  .btn {
    padding: 4px 15px;
    font-size: 14px;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s ease;
    border: 1px solid transparent;
    outline: none;
  }
  
  .btn-default {
    background: #fff;
    border-color: #d9d9d9;
    color: #262626;
  }
  
  .btn-default:hover {
    border-color: #40a9ff;
    color: #40a9ff;
  }
  
  .btn-primary {
    background: #1890ff;
    border-color: #1890ff;
    color: #fff;
  }
  
  .btn-primary:hover {
    background: #40a9ff;
    border-color: #40a9ff;
  }
  
  .btn-danger {
    background: #ff4d4f;
    border-color: #ff4d4f;
    color: #fff;
  }
  
  .btn-danger:hover {
    background: #ff7875;
    border-color: #ff7875;
  }

/* 头部信息 */
.header-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.subtitle {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  margin: 0;
}

/* 阶段容器 */
.stages-container {
  padding: 20px;
}

.stages-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 阶段项目 */
.stage-item {
  border: 2px solid var(--border-base);
  border-radius: var(--border-radius-md);
  padding: 20px;
  background-color: var(--bg-white);
  transition: all 0.3s ease;
}

.stage-item:hover {
  border-color: var(--primary-color);
  box-shadow: var(--shadow-md);
}

.stage-item.dragging {
  opacity: 0.7;
  transform: scale(1.02);
}

/* 阶段头部 */
.stage-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid var(--border-light);
}

.stage-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.stage-number {
  width: 36px;
  height: 36px;
  background-color: var(--primary-color);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: var(--font-size-md);
}

.stage-name {
  font-size: var(--font-size-lg);
  font-weight: 600;
  color: var(--text-primary);
}

/* 阶段操作按钮 */
.stage-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.move-buttons {
  display: flex;
  gap: 5px;
}

/* 阶段任务区域 */
.stage-tasks {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.section-title {
  font-weight: 600;
  color: var(--text-primary);
  font-size: var(--font-size-md);
  margin-bottom: 10px;
}

/* 已选任务标签 */
.selected-tasks {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  margin-bottom: 15px;
}

.task-tag {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  background-color: var(--primary-color);
  color: white;
  padding: 6px 12px;
  border-radius: var(--border-radius-sm);
  font-size: var(--font-size-sm);
  font-weight: 500;
}

.remove-task-btn {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  font-size: var(--font-size-md);
  line-height: 1;
  padding: 0;
  width: 18px;
  height: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s ease;
}

.remove-task-btn:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

/* 可选任务列表 */
.available-tasks {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.task-checkbox {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: var(--border-radius-sm);
  transition: background-color 0.2s ease;
}

.task-checkbox:hover {
  background-color: var(--bg-hover);
}

.task-checkbox input[type="checkbox"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.task-label {
  font-size: var(--font-size-base);
  color: var(--text-regular);
}

/* 投产情况汇总样式 */
.summary-container {
  padding: 20px;
}

/* 搜索栏样式 */
.search-bar {
  background-color: var(--bg-light);
  border-bottom: 1px solid var(--border-light);
  padding: 20px;
}

.search-fields {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
}

.search-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
  min-width: 200px;
}

.search-label {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
}

.search-actions {
  display: flex;
  gap: 10px;
}

/* 搜索结果区域 */
.search-results {
  margin-top: 20px;
}

.result-section {
  margin-bottom: 20px;
  border: 1px solid var(--border-base);
  border-radius: var(--border-radius-md);
  overflow: hidden;
}

.result-header {
  padding: 15px 20px;
  background-color: var(--bg-light);
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.result-header:hover {
  background-color: var(--bg-hover);
}

.result-header h4 {
  margin: 0;
  font-size: var(--font-size-md);
  color: var(--text-primary);
}

.expand-icon {
  transition: transform 0.3s ease;
}

.result-content {
  padding: 20px;
  background-color: var(--bg-white);
}

/* 流程阶段展示 */
.process-flow {
  margin-bottom: 30px;
  padding: 20px;
  background-color: var(--bg-white);
  border-radius: var(--border-radius-md);
  border: 1px solid var(--border-base);
}

.process-flow h4 {
  font-size: var(--font-size-lg);
  color: var(--text-primary);
  margin-bottom: 20px;
}

.flow-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative;
  padding: 20px 0;
}

.flow-stage {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  z-index: 2;
}

.clickable-stage {
  cursor: pointer;
  transition: transform 0.2s ease;
}

.clickable-stage:hover {
  transform: scale(1.05);
}

.stage-dot {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: var(--primary-color);
  margin-bottom: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
}

.stage-dot.completed {
  background-color: var(--success-color);
  transform: scale(1.2);
}

.stage-name {
  font-size: var(--font-size-sm);
  color: var(--text-primary);
  text-align: center;
  max-width: 120px;
}

.stage-line {
  position: absolute;
  top: 10px;
  left: calc(100% + 10px);
  width: calc(100% - 60px);
  height: 2px;
  background-color: var(--border-base);
  z-index: 1;
}

/* 响应式调整 - 搜索栏 */
@media (max-width: 768px) {
  .search-fields {
    flex-direction: column;
  }
  
  .search-item {
    min-width: 100%;
  }
  
  .flow-container {
    flex-direction: column;
    gap: 20px;
  }
  
  .stage-line {
    position: relative;
    top: auto;
    left: auto;
    width: 2px;
    height: 30px;
    margin: 10px 0;
  }
}

/* 进度概览 */
.progress-overview {
  margin-bottom: 30px;
}

.progress-card {
  background-color: var(--bg-light);
  border-radius: var(--border-radius-md);
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.progress-percentage {
  font-size: 36px;
  font-weight: 700;
  color: var(--primary-color);
}

.progress-label {
  font-size: var(--font-size-md);
  color: var(--text-secondary);
}

.progress-bar {
  width: 100%;
  height: 8px;
  background-color: rgba(255, 255, 255, 0.5);
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background-color: var(--primary-color);
  transition: width 0.5s ease;
}

/* 指标卡片 */
.metrics-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.metric-card {
  background-color: var(--bg-white);
  border: 1px solid var(--border-base);
  border-radius: var(--border-radius-md);
  padding: 20px;
  text-align: center;
  transition: all 0.3s ease;
}

.metric-card:hover {
  box-shadow: var(--shadow-md);
  transform: translateY(-2px);
}

.metric-card.success {
  border-color: var(--success-color);
}

.metric-card.warning {
  border-color: var(--warning-color);
}

.metric-value {
  font-size: 32px;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 8px;
}

.metric-label {
  font-size: var(--font-size-base);
  color: var(--text-secondary);
}

/* 时间信息 */
.timeline-info {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.time-item {
  background-color: var(--bg-white);
  border: 1px solid var(--border-base);
  border-radius: var(--border-radius-md);
  padding: 15px 20px;
}

.time-label {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  margin-bottom: 5px;
}

.time-value {
  font-size: var(--font-size-md);
  color: var(--text-primary);
  font-weight: 500;
}

.time-value.current {
  color: var(--primary-color);
  font-weight: 600;
}

/* 问题列表 */
.issues-section {
  margin-top: 30px;
}

.issues-section h4 {
  font-size: var(--font-size-lg);
  color: var(--text-primary);
  margin-bottom: 15px;
}

.issues-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.issue-item {
  display: flex;
  align-items: center;
  gap: 20px;
  background-color: var(--bg-white);
  border: 1px solid var(--border-base);
  border-radius: var(--border-radius-md);
  padding: 15px 20px;
  transition: all 0.3s ease;
}

.issue-item:hover {
  box-shadow: var(--shadow-sm);
}

.issue-item.solved {
  border-color: var(--success-color);
  background-color: rgba(22, 163, 74, 0.05);
}

.issue-stage {
  min-width: 100px;
  font-weight: 600;
  color: var(--text-primary);
}

.issue-description {
  flex: 1;
  color: var(--text-regular);
}

.issue-status {
  font-size: var(--font-size-sm);
  font-weight: 500;
  padding: 4px 12px;
  border-radius: 20px;
  background-color: var(--bg-light);
}

/* 消息容器 */
.message-container {
  position: fixed;
  top: 80px;
  right: 20px;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  gap: 10px;
  max-width: 360px;
}

/* 动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .route-simulation {
    padding: 10px;
  }
  
  .stages-container {
    padding: 10px;
  }
  
  .stage-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .stage-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .metrics-cards,
  .timeline-info {
    grid-template-columns: 1fr;
  }
  
  .available-tasks {
    flex-direction: column;
  }
  
  .issue-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}

/* 模态框样式增强 */
.modal-content-lg {
  max-width: 800px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

/* 确认删除模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  width: 480px;
  max-width: 90%;
  overflow: hidden;
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
}

.modal-body {
  padding: 24px;
}

.modal-body p {
  margin: 0;
  color: #595959;
  font-size: 14px;
}

.modal-footer {
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 子任务进度样式 */
.subtasks-progress {
  margin-bottom: 30px;
}

.subtasks-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.subtask-item {
  padding: 15px;
  background-color: var(--bg-light);
  border-radius: var(--border-radius-md);
}

.subtask-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.subtask-name {
  font-size: var(--font-size-md);
  color: var(--text-primary);
  font-weight: 500;
}

.subtask-percentage {
  font-size: var(--font-size-md);
  font-weight: 600;
  color: var(--primary-color);
}


/* 处理人统计样式 */
  .processors-statistics {
    margin-bottom: 20px;
  }
  
  .processors-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  
  .processor-item {
    padding: 15px;
    background-color: var(--bg-white);
    border: 1px solid var(--border-base);
    border-radius: var(--border-radius-md);
  }
  
  .processor-name {
    font-weight: 500;
    color: var(--text-primary);
    margin-bottom: 10px;
  }
  
  .processor-stats {
    display: flex;
    gap: 20px;
    margin-bottom: 10px;
  }
  
  .stat-item {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }
  
  .stat-label {
    font-size: var(--font-size-sm);
    color: var(--text-secondary);
  }
  
  .stat-value {
    font-size: var(--font-size-base);
    font-weight: 600;
    color: var(--text-primary);
  }
  
  .stat-value.solved {
    color: var(--success-color);
  }
  
  .stat-value.pending {
    color: var(--warning-color);
  }
  
  /* 进度条样式 */
  .progress-bar {
    width: 100%;
    height: 8px;
    background-color: #f0f0f0;
    border-radius: 4px;
    overflow: hidden;
    display: flex;
  }
  
  .progress-fill {
    height: 100%;
    transition: width 0.3s ease;
  }
  
  .progress-fill.solved {
    background-color: #52c41a; /* 绿色 - 已解决 */
  }
  
  .progress-fill.pending {
    background-color: #faad14; /* 橙色 - 未解决 */
  }

  .progress-fill.pending {
    background-color: #faad14; /* 橙色 - 未解决 */
  }
</style>